#include "stdafx.h"
#include "exportMesh.h"
#include "mesh.h"

extern HINSTANCE g_hInstance;

//////////
// ExportMeshCmd
void* ExportMeshCmd::Create()
{
	return new ExportMeshCmd;
}

MStatus ExportMeshCmd::doIt(const MArgList &args)
{
	try
	{
		ParseArguments(args);

		MSpace::Space space = worldSpace ? MSpace::kWorld : MSpace::kObject;
		Mesh mesh;
		assert(meshPaths.size() > 0);
		for(int i = 0;i < (int)meshPaths.size();i++)
		{
			Mesh curMesh(meshPaths[i],space);
			mesh.Union(curMesh);
		}	

		switch(fileFormat)
		{
		case Binary:
			mesh.WriteToBinary(outFileName);
			break;
		case Xml:
			mesh.WriteToXml(outFileName);
			break;
		}		

		MGlobal::displayInfo(("Mesh successfully exported to " + outFileName).c_str());
		return MStatus::kSuccess;
	}
	catch(const Exception &err)
	{
		MGlobal::displayError(err.GetErrorMessage().c_str());
		return MStatus::kFailure;
	}
}

void ExportMeshCmd::ParseArguments(const MArgList &args)
{
	MayaArgParser parser("exportMesh");
	parser.AddFlag("ws","worldSpace",MayaArgParser::FLAG);
	parser.AddFlag("os","objectSpace",MayaArgParser::FLAG);
	parser.AddFlag("o","outFile",MayaArgParser::STRING);
	parser.SetNodeArgHandling(1,INT_MAX,true);
	parser.Parse(args);

	if(parser.IsFlagSet("os"))
	{
		worldSpace = false;
		if(parser.IsFlagSet("ws"))
		{
			throw Exception("You should't specify both the -ws/-worldSpace "
				"and -o/-objectSpace flag to the exportMesh command");
		}
	}
	else
		worldSpace = true;

	meshPaths = parser.GetNodeArgs();

	if(parser.IsFlagSet("o"))
	{
		outFileName = parser.GetFlagString("o");
		fileFormat = Xml;
	}
	else
	{
		// the o flag isn't specified, so we prompt an file dialog.

		char fileName[MAX_PATH];
		char fileTitle[MAX_PATH];
		char defExtension[1024];
		
		strcpy(fileName,"");
		strcpy(fileTitle,"");
		strcpy(defExtension,"");

		OPENFILENAME ofn;
		memset(&ofn,0,sizeof(OPENFILENAME));
		ofn.lStructSize = sizeof(OPENFILENAME);
		ofn.hwndOwner = 0;
		ofn.hInstance = g_hInstance;
		ofn.lpstrFilter = "Dida mesh binary (*.dmb)\0*.dmb\0"
			"Dida mesh xml (*.dmx)\0*.dmx\0";
		ofn.nFilterIndex = 0;
		ofn.lpstrFile = fileName;
		ofn.nMaxFile = MAX_PATH;
		ofn.lpstrFileTitle = fileTitle;
		ofn.nMaxFileTitle = MAX_PATH;
		ofn.lpstrTitle = "Save mesh to";
		ofn.Flags = OFN_HIDEREADONLY;
		ofn.lpstrDefExt = defExtension;
		if(GetSaveFileName(&ofn))
		{
			outFileName = fileName;
			
			if(ofn.nFileExtension == 0)
				fileFormat = Binary;
			else
			{
				if(strcmp(fileName + ofn.nFileExtension,"dmx") == 0)
					fileFormat = Xml;
				else
					fileFormat = Binary;
			}
		}
		else
			throw Exception("No output file specified");
	}
}